package controllers.terminal;
import hprose.HproseClinetService;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import play.Logger;
import play.cache.Cache;
import utils.file.DownExcel;
import utils.file.ExportExcel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ning.http.util.Base64;
import com.ning.http.util.DateUtil;

import component.UserBis;
import constants.APIConstants;
import controllers.common.filter.BaseFilter;

/**
 * 终端库存
 * 2015年12月3日 下午3:36:00
 * @author huan208050@vip.qq.com
 */
public class TermialInventoryAction extends BaseFilter {
	/**
	 * 查询所有终端列表
	 * 
	 * 2015年12月3日 下午3:36:08
	 * @auth huan208050@vip.qq.com
	 */
	public static void index(){
	 render();
	}
	
	public static void getInventoryAllList(){
		String custId = UserBis.currUser();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customer_id", custId);
		paramMap.put("currPage", params.get("currPage"));
		paramMap.put("pageSize", params.get("pageSize"));
		paramMap.put("isAll", params.get("isAll"));
		paramMap.put("isPage", "1");
		Object [] arguments = new Object[]{paramMap};
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETSAFEINVENTORYLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject safes = JSONObject.parseObject(res);
		renderJSON(safes);
	}
	
	/**
	 *  库存列表导出Excel
	 * 
	 * 2016年3月18日 下午4:18:34
	 * @auth liqi
	 */
	public static void doExcel(){
		String custId = UserBis.currUser();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customer_id", custId);
		paramMap.put("currPage", params.get("currPage"));
		paramMap.put("pageSize", params.get("pageSize"));
		paramMap.put("isAll", params.get("isAll"));
		paramMap.put("isPage", "0");
		Object [] arguments = new Object[]{paramMap};
		
        String res = HproseClinetService.synCall(APIConstants.TIMSI_GETSAFEINVENTORYLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
        JSONObject json = JSONObject.parseObject(res);
        List<Map<String,Object>> list = (List<Map<String,Object>>)json.get("data");
        
        HSSFWorkbook wb = DownExcel.downExcel("库存列表", "物料编码:规格简称:规格全称:供应商:当前库存:安全库存:领用数量:回收数量:统计日期", 
        		"customer_specs_no:simple_specs_cust:long_specs_cust:supp_name:now_num:safe_num:use_num:rec_num:date", list);
        // 生成文件名
        String fileName = "CutterUse" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xls";
        try {
            response.setContentTypeIfNotSet("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "GB2312"));
            OutputStream out = response.out;
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            list.clear();
        }
		
	}
	/**
	 * 获取刀具
	 * @Title:        cutterUseIndex 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param material_id
	 * @param:        @param date    
	 * @return:       void    
	 * @throws 
	 * @author        caofan
	 * @Date          2015年12月29日 上午9:50:50
	 */
	public static void cutterUseIndex(String material_id){
		render(material_id);
	}
	/**
	 * 获取刀具使用回收列表
	 * @Title:        CutterUseDetail 
	 * @Description:  TODO(这里用一句话描述这个方法的作用) 
	 * @param:        @param material_id
	 * @param:        @param date    
	 * @return:       void    
	 * @throws 
	 * @author        caofan
	 * @Date          2015年12月16日 下午5:23:33
	 */
	public static void cutterUseDetail(){
		String custId = UserBis.currUser();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customer_id",custId);
		paramMap.put("material_id", params.get("material_id"));
		paramMap.put("operator_id", params.get("operator_id"));
		paramMap.put("currPage", params.get("currPage"));
		paramMap.put("pageSize", params.get("pageSize"));
		Object [] arguments = new Object[]{paramMap};
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETCUTTERUSELIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject cutters = JSONObject.parseObject(res);
		renderJSON(cutters);
	}
	
	/**
	 * Excel导出刀具使用回收列表
	 * 
	 * 2016年5月6日 上午10:33:39
	 * @auth liqi
	 */
	public static void downCutterUseDetail(){
		String custId = UserBis.currUser();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customer_id",custId);
		paramMap.put("material_id", params.get("mid"));
		paramMap.put("isPage", "-1");
		
		Object [] arguments = new Object[]{paramMap};
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETCUTTERUSELIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
 	JSONObject cutters = JSONObject.parseObject(res);
		List<Map<String,Object>> list = (List<Map<String,Object>>)cutters.get("data");
        
        HSSFWorkbook wb = DownExcel.downExcel("库存详情列表", "物料编码:规格简称:规格全称:供应商:操作人:操作数量:操作类型:操作时间", 
        		"customer_specs_no:simple_specs_cust:long_specs_cust:supp_name:real_name:num:type:time", list);
        // 生成文件名
        String fileName = "InventoryDetail" + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xls";
        try {
            response.setContentTypeIfNotSet("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "GB2312"));
            OutputStream out = response.out;
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            list.clear();
        }
	}
	/**
	 * 库存详情
	 * 
	 * 2015年12月3日 下午3:36:28
	 * @auth huan208050@vip.qq.com
	 */
	public static void inventoryDetails(String tid){
		String custId = Cache.get("user_no",String.class);
		Map<String, Object> map = new HashMap<String, Object>();
		Object[] arguments = new Object[]{map};
		map.put("terminal_id", tid);
		map.put("customer_id", custId);
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETLASTINVENTORYBYTERMINALID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject json = JSONObject.parseObject(res);
		List<Map<String,Object>> list = (List<Map<String,Object>>)json.get("data");
		render(list);
//		StringBuffer sql = new StringBuffer();
//		Map<String, Object> condition = new HashMap<String, Object>();
//		sql.append("SELECT "
//				+ "t1.terminal_id as terminal_id, "
//				+ "t1.customer_id as customer_id, "
//				+ "t1.material_id as material_id, "
//				+ "t2.cutter_specs as cutter_specs, "
//				+ "sum(t1.num) as num, "
//				+ "DATE_FORMAT(t1.time, '%Y-%m-%d %T') as time "
//				+ "FROM terminalinventory t1 "
//				+ "LEFT JOIN cutterspecs t2 "
//				+ "ON t1.material_id = t2.cust_cutter_spesc_id "
//				+ "GROUP BY t1.material_id HAVING t1.customer_id=:cid and t1.terminal_id=:tid");
//		condition.put("cid", custId);
//		condition.put("tid", tid);
//		String [] keys = {"terminal_id","customer_id","material_id","cutter_specs","num","time"};
//		String res = DbUtils.queryPartialField(sql.toString(), keys,condition);
//		Logger.info("res-->"+res);
//		JSONObject json = JSONObject.parseObject(res);
//		List<Map<String,Object>> list = (List<Map<String,Object>>)json.get("data");
//		render(list);
	}
	/**
	 * 终端状态
	 * 传入terminal_id，customer_id
	 * 2016年1月27日 上午9:39:55
	 * @auth huan208050@vip.qq.com
	 */
	public static void terminalStatus(){
		/**
		 * 1.查询终端中的信息
		 */
		
		render();
	}
	/**
	 * 终端列表获取
	 * customer_id
	 * 
	 * 2016年1月27日 上午11:24:53
	 * @auth huan208050@vip.qq.com
	 */
	public static void getTerminalList(){
		JSONObject json = new JSONObject();
		String customer_id = UserBis.currUser();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", customer_id);
		Object[] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.TMI_GETTERMINALBYCONDITION, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		json = JSONObject.parseObject(res);
		Logger.info(json.toJSONString());
		renderJSON(json.get("data"));
	}
	
	
	public static void terminalInfoIndex(String terminal_id){
		render(terminal_id);
	}
	
	
	public static void getTerminalInfoByTerminalId(){
		String terminal_id = params.get("terminal_id");
		/*JSONArray ja = new JSONArray();
		JSONObject json1 = new JSONObject();
		json1.put("code", "code1_"+terminal_id);
		json1.put("name", "name1_"+terminal_id);
		json1.put("status", "1000");
		json1.put("msg", "正常"+terminal_id);
		ja.add(json1);
		
		JSONObject json2 = new JSONObject();
		json2.put("code", "code2_"+terminal_id);
		json2.put("name", "name2_"+terminal_id);
		json2.put("status", "1001");
		json2.put("msg", "门锁通电异常"+terminal_id);
		ja.add(json2);*/
		
		JSONObject json = new JSONObject();
		String customer_id = UserBis.currUser();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", customer_id);
		map.put("terminal_id", terminal_id);
		Object[] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.TMI_GETTERMINALSTATUS, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		json = JSONObject.parseObject(res);
		Logger.info(json.toJSONString());
		renderJSON(json.get("data"));
	}
	
	public static void terminaInventoryIndex(String terminal_id){
		render(terminal_id);
	}	
	
	public static void getTerminalInventoryByTerminalId(){
		String terminal_id = params.get("terminal_id");
		JSONObject json = new JSONObject();
		String customer_id = UserBis.currUser();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", customer_id);
		map.put("terminal_id", terminal_id);
		Object[] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.TIMSI_GETINVENTORYBYTERMINALID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		json = JSONObject.parseObject(res);
		Logger.info(json.toJSONString());
		renderJSON(json);
	}
	/**
	 * 根据刀具获取柜子库存
	 */
	public static void getOtherTerminalCutterInventoryByCustomerId(){
		JSONObject json = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			System.out.println(params.get("customer_id"));
			System.out.println(params.get("material_id"));
			String customer_id = new String(Base64.decode(params.get("customer_id")),"UTF-8");
			String material_id = new String(Base64.decode(params.get("material_id")),"UTF-8");
			map.put("customer_id", customer_id);
			map.put("material_id", material_id);
			Object[] arguments = new Object[]{map};
			String res = HproseClinetService.synCall(APIConstants.TIMSI_GETINVENTORYBYCUSTOMERIDANDMATERIELID, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			json = JSONObject.parseObject(res);
			Logger.info(json.toJSONString());
			renderJSON(json);
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
	}
	
}



















